{% extends "base.html" %}

{% block content %}
<div class="max-w-7xl mx-auto">
    <!-- Header -->
    <div class="mb-8">
        <h1 class="text-2xl font-bold text-gray-900">FDA Device Data Analysis</h1>
        <p class="text-gray-600">Automated data collection and analysis from openFDA API</p>
    </div>

    <!-- Product Code Selection -->
    <div class="bg-white rounded-xl shadow-sm border border-gray-200 p-6 mb-6">
        <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
            <!-- Main Analysis Selection -->
            <div>
                <div class="flex items-center justify-between mb-4">
                    <h2 class="text-lg font-semibold text-gray-900">Product Code Selection</h2>
                    <button onclick="showAddCodeModal('analysis')" class="px-3 py-1.5 bg-indigo-600 text-white rounded-lg hover:bg-indigo-700 text-sm flex items-center space-x-2">
                        <i class="fas fa-plus text-xs"></i>
                        <span>Add New Code</span>
                    </button>
                </div>
                
                <label class="block text-sm font-medium text-gray-700 mb-2">Select Product Code for Analysis</label>
                <div class="flex items-center space-x-3">
                    <div class="relative flex-1">
                        <select id="selectedProductCode" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500 appearance-none bg-white">
                            <!-- Options will be loaded dynamically -->
                        </select>
                        <div class="pointer-events-none absolute inset-y-0 right-0 flex items-center px-2 text-gray-700">
                            <i class="fas fa-chevron-down"></i>
                        </div>
                    </div>
                    <button onclick="loadAllData()" class="px-4 py-2 bg-indigo-600 text-white rounded-lg hover:bg-indigo-700 flex items-center space-x-2 whitespace-nowrap">
                        <i class="fas fa-sync-alt"></i>
                        <span>Load Data</span>
                    </button>
                </div>
                
                <div class="mt-3 grid grid-cols-7 gap-2" id="productChipsContainer">
                    <!-- Product chips will be dynamically added -->
                </div>
            </div>
            
            <!-- Comparison Selection -->
            <div>
                <h2 class="text-lg font-semibold text-gray-900 mb-4">Product Comparison</h2>
                <div class="grid grid-cols-2 gap-4">
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-2">Product A</label>
                        <select id="compareProductA" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500">
                            <!-- Options will be loaded dynamically -->
                        </select>
                    </div>
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-2">Product B</label>
                        <select id="compareProductB" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500">
                            <!-- Options will be loaded dynamically -->
                        </select>
                    </div>
                </div>
                <button onclick="loadComparisonData()" class="mt-4 px-4 py-2 bg-purple-600 text-white rounded-lg hover:bg-purple-700 w-full flex items-center justify-center space-x-2">
                    <i class="fas fa-balance-scale"></i>
                    <span>Compare Products</span>
                </button>
            </div>
        </div>
        
        <div class="mt-6 pt-6 border-t border-gray-200">
            <label class="block text-sm font-medium text-gray-700 mb-2">Time Range</label>
            <div class="flex items-center space-x-4">
                <input type="date" id="startDate" value="2010-01-01" class="px-3 py-2 border border-gray-300 rounded-lg">
                <span class="text-gray-500">to</span>
                <input type="date" id="endDate" value="2025-12-31" class="px-3 py-2 border border-gray-300 rounded-lg">
            </div>
        </div>
    </div>

    <!-- Tab Navigation -->
    <div class="bg-white rounded-xl shadow-sm border border-gray-200 mb-6">
        <div class="border-b border-gray-200">
            <nav class="flex space-x-8 px-6" aria-label="Tabs">
                <button onclick="switchTab('510k')" class="tab-button active border-b-2 border-indigo-600 py-4 px-1 text-sm font-medium text-indigo-600">
                    510(k) Latest Records
                </button>
                <button onclick="switchTab('adverse')" class="tab-button border-b-2 border-transparent py-4 px-1 text-sm font-medium text-gray-500 hover:text-gray-700 hover:border-gray-300">
                    Adverse Event Analysis
                </button>
                <button onclick="switchTab('recall')" class="tab-button border-b-2 border-transparent py-4 px-1 text-sm font-medium text-gray-500 hover:text-gray-700 hover:border-gray-300">
                    Recall Analysis
                </button>
                <button onclick="switchTab('compare')" class="tab-button border-b-2 border-transparent py-4 px-1 text-sm font-medium text-gray-500 hover:text-gray-700 hover:border-gray-300">
                    Product Comparison
                </button>
            </nav>
        </div>
    </div>

    <!-- 510(k) Tab -->
    <div id="tab-510k" class="tab-content">
        <div class="bg-white rounded-xl shadow-sm border border-gray-200 p-6 mb-6">
            <div class="flex items-center justify-between mb-4">
                <div>
                    <h3 class="text-lg font-semibold text-gray-900">Latest 510(k) Records</h3>
                    <p class="text-sm text-gray-500">
                        Product Code: <span id="510k-product-code" class="font-medium">--</span>
                        | Total: <span id="510k-total" class="font-medium">0</span>
                        | Last Updated: <span id="510k-last-updated">--</span>
                    </p>
                </div>
                <button onclick="load510kData()" class="px-4 py-2 bg-indigo-600 text-white rounded-lg hover:bg-indigo-700 flex items-center space-x-2">
                    <i class="fas fa-sync-alt"></i>
                    <span>Refresh</span>
                </button>
            </div>
            
            <div id="510k-loading" class="hidden text-center py-8">
                <div class="animate-spin rounded-full h-8 w-8 border-b-2 border-indigo-600 mx-auto"></div>
                <p class="mt-2 text-gray-500">Loading 510(k) data...</p>
            </div>
            
            <div id="510k-table" class="overflow-x-auto"></div>
        </div>
    </div>

    <!-- Adverse Events Tab -->
    <div id="tab-adverse" class="tab-content hidden">
        <div class="grid grid-cols-1 lg:grid-cols-2 gap-6 mb-6">
            <!-- Event Type Chart -->
            <div class="bg-white rounded-xl shadow-sm border border-gray-200 p-6">
                <h3 class="text-lg font-semibold text-gray-900 mb-4">Event Type Distribution</h3>
                <div class="text-center text-sm text-gray-500 mb-2" id="adverse-product-code">Product Code: --</div>
                <canvas id="eventTypeChart"></canvas>
            </div>
            
            <!-- Report Source Chart -->
            <div class="bg-white rounded-xl shadow-sm border border-gray-200 p-6">
                <h3 class="text-lg font-semibold text-gray-900 mb-4">Report Source Distribution</h3>
                <div class="text-center text-sm text-gray-500 mb-2">Total Events: <span id="adverse-total" class="font-medium">0</span></div>
                <canvas id="reportSourceChart"></canvas>
            </div>
        </div>
        
        <!-- Annual Trends -->
        <div class="bg-white rounded-xl shadow-sm border border-gray-200 p-6 mb-6">
            <div class="flex items-center justify-between mb-4">
                <h3 class="text-lg font-semibold text-gray-900">Annual Adverse Event Trends</h3>
                <button onclick="loadAdverseEventData()" class="px-4 py-2 bg-indigo-600 text-white rounded-lg hover:bg-indigo-700 flex items-center space-x-2">
                    <i class="fas fa-sync-alt"></i>
                    <span>Refresh</span>
                </button>
            </div>
            <canvas id="adverseTrendChart"></canvas>
        </div>
        
        <div id="adverse-loading" class="hidden text-center py-8">
            <div class="animate-spin rounded-full h-8 w-8 border-b-2 border-indigo-600 mx-auto"></div>
            <p class="mt-2 text-gray-500">Loading adverse event data...</p>
        </div>
    </div>

    <!-- Recall Tab -->
    <div id="tab-recall" class="tab-content hidden">
        <div class="grid grid-cols-1 lg:grid-cols-2 gap-6 mb-6">
            <!-- Classification Chart -->
            <div class="bg-white rounded-xl shadow-sm border border-gray-200 p-6">
                <h3 class="text-lg font-semibold text-gray-900 mb-4">Recall Classification</h3>
                <div class="text-center text-sm text-gray-500 mb-2" id="recall-product-code">Product Code: --</div>
                <canvas id="classificationChart"></canvas>
            </div>
            
            <!-- Status Chart -->
            <div class="bg-white rounded-xl shadow-sm border border-gray-200 p-6">
                <h3 class="text-lg font-semibold text-gray-900 mb-4">Recall Status</h3>
                <div class="text-center text-sm text-gray-500 mb-2">Total Recalls: <span id="recall-total" class="font-medium">0</span></div>
                <canvas id="statusChart"></canvas>
            </div>
        </div>
        
        <!-- Root Causes -->
        <div class="bg-white rounded-xl shadow-sm border border-gray-200 p-6 mb-6">
            <div class="flex items-center justify-between mb-4">
                <h3 class="text-lg font-semibold text-gray-900">Root Cause Analysis</h3>
                <button onclick="loadRecallData()" class="px-4 py-2 bg-indigo-600 text-white rounded-lg hover:bg-indigo-700 flex items-center space-x-2">
                    <i class="fas fa-sync-alt"></i>
                    <span>Refresh</span>
                </button>
            </div>
            <canvas id="rootCauseChart"></canvas>
        </div>
        
        <div id="recall-loading" class="hidden text-center py-8">
            <div class="animate-spin rounded-full h-8 w-8 border-b-2 border-indigo-600 mx-auto"></div>
            <p class="mt-2 text-gray-500">Loading recall data...</p>
        </div>
    </div>

    <!-- Comparison Tab -->
    <div id="tab-compare" class="tab-content hidden">
        <div class="bg-white rounded-xl shadow-sm border border-gray-200 p-6 mb-6">
            <div class="flex items-center justify-between mb-6">
                <div>
                    <h3 class="text-lg font-semibold text-gray-900">Product Comparison</h3>
                    <p class="text-sm text-gray-500" id="comparison-codes">Comparing: -- vs --</p>
                </div>
                <button onclick="loadComparisonData()" class="px-4 py-2 bg-purple-600 text-white rounded-lg hover:bg-purple-700 flex items-center space-x-2">
                    <i class="fas fa-sync-alt"></i>
                    <span>Refresh</span>
                </button>
            </div>
            
            <div id="comparison-loading" class="hidden text-center py-8">
                <div class="animate-spin rounded-full h-8 w-8 border-b-2 border-purple-600 mx-auto"></div>
                <p class="mt-2 text-gray-500">Loading comparison data...</p>
            </div>
            
            <!-- Comparison Metrics -->
            <div class="grid grid-cols-1 md:grid-cols-3 gap-6 mb-8" id="comparison-metrics">
                <!-- Will be filled dynamically -->
            </div>
            
            <!-- Comparison Charts -->
            <div class="space-y-6">
                <div>
                    <h4 class="text-md font-semibold text-gray-900 mb-4">Adverse Events vs Recalls</h4>
                    <canvas id="comparisonChart1"></canvas>
                </div>
                <div class="grid grid-cols-1 lg:grid-cols-2 gap-6">
                    <div>
                        <h4 class="text-md font-semibold text-gray-900 mb-4">Latest 510(k) Decision Dates</h4>
                        <canvas id="comparisonChart2"></canvas>
                    </div>
                    <div>
                        <h4 class="text-md font-semibold text-gray-900 mb-4">Safety Metrics Summary</h4>
                        <canvas id="comparisonChart3"></canvas>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Export Options -->
    <div class="bg-white rounded-xl shadow-sm border border-gray-200 p-4 flex items-center justify-between">
        <div class="flex items-center space-x-4">
            <span class="text-sm text-gray-600">Export data:</span>
            <button onclick="exportToCSV()" class="px-3 py-1.5 border border-gray-300 text-gray-700 rounded hover:bg-gray-50 text-sm flex items-center space-x-2">
                <i class="fas fa-file-csv"></i>
                <span>CSV</span>
            </button>
            <button onclick="exportToExcel()" class="px-3 py-1.5 border border-gray-300 text-gray-700 rounded hover:bg-gray-50 text-sm flex items-center space-x-2">
                <i class="fas fa-file-excel"></i>
                <span>Excel</span>
            </button>
        </div>
        <div class="text-sm text-gray-500">
            Data Source: <a href="https://open.fda.gov" target="_blank" class="text-indigo-600 hover:text-indigo-800">openFDA API</a>
        </div>
    </div>
</div>

<!-- Add Product Code Modal -->
<div id="addCodeModal" class="hidden fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
    <div class="bg-white rounded-xl shadow-xl max-w-md w-full mx-4 p-6">
        <h3 class="text-xl font-semibold text-gray-900 mb-4" id="modalTitle">Add Product Code</h3>
        <input type="hidden" id="modalContext" value="">
        <input type="text" id="newCodeInput" placeholder="Enter product code (e.g., OHV, GEX)" maxlength="10" class="w-full px-3 py-2 border border-gray-300 rounded-lg mb-4">
        <div class="flex items-center justify-end space-x-3">
            <button onclick="closeAddCodeModal()" class="px-4 py-2 border border-gray-300 text-gray-700 rounded-lg hover:bg-gray-50">Cancel</button>
            <button onclick="confirmAddCode()" class="px-4 py-2 bg-indigo-600 text-white rounded-lg hover:bg-indigo-700">Add</button>
        </div>
    </div>
</div>
{% endblock %}

{% block scripts %}
<script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.0/dist/chart.umd.min.js"></script>
<script>
let availableCodes = [];
let selectedCode = '';
let comparisonCodes = { A: '', B: '' };
let charts = {};

document.addEventListener('DOMContentLoaded', () => {
    loadProductCodes();
});

async function loadProductCodes() {
    try {
        const response = await fetch('/api/fda/product-codes');
        const data = await response.json();
        
        if (data.status === 'success') {
            availableCodes = data.product_codes;
            selectedCode = availableCodes[0] || '';
            comparisonCodes.A = availableCodes[0] || '';
            comparisonCodes.B = availableCodes[1] || '';
            renderProductSelectors();
            renderProductChips();
            loadAllData();
        }
    } catch (error) {
        console.error('Error loading product codes:', error);
    }
}

function renderProductSelectors() {
    const analysisSelect = document.getElementById('selectedProductCode');
    const compareSelectA = document.getElementById('compareProductA');
    const compareSelectB = document.getElementById('compareProductB');
    
    analysisSelect.innerHTML = '';
    compareSelectA.innerHTML = '';
    compareSelectB.innerHTML = '';
    
    availableCodes.forEach(code => {
        const option1 = document.createElement('option');
        option1.value = code;
        option1.textContent = code;
        option1.selected = (code === selectedCode);
        analysisSelect.appendChild(option1);
        
        const option2 = document.createElement('option');
        option2.value = code;
        option2.textContent = code;
        option2.selected = (code === comparisonCodes.A);
        compareSelectA.appendChild(option2);
        
        const option3 = document.createElement('option');
        option3.value = code;
        option3.textContent = code;
        option3.selected = (code === comparisonCodes.B);
        compareSelectB.appendChild(option3);
    });
    
    // Add change event listeners
    analysisSelect.addEventListener('change', function() {
        selectedCode = this.value;
        loadAllData();
    });
    
    compareSelectA.addEventListener('change', function() {
        comparisonCodes.A = this.value;
        updateComparisonDisplay();
    });
    
    compareSelectB.addEventListener('change', function() {
        comparisonCodes.B = this.value;
        updateComparisonDisplay();
    });
}

function renderProductChips() {
    const container = document.getElementById('productChipsContainer');
    container.innerHTML = '';
    
    availableCodes.forEach(code => {
        const chip = document.createElement('div');
        chip.className = code === selectedCode 
            ? 'bg-indigo-600 text-white px-2 py-1 rounded text-sm text-center cursor-pointer'
            : 'bg-gray-100 text-gray-800 px-2 py-1 rounded text-sm text-center cursor-pointer hover:bg-gray-200';
        chip.textContent = code;
        chip.title = `Click to select ${code}`;
        chip.onclick = () => {
            selectedCode = code;
            document.getElementById('selectedProductCode').value = code;
            renderProductChips();
            loadAllData();
        };
        container.appendChild(chip);
    });
}

function showAddCodeModal(context) {
    document.getElementById('modalContext').value = context;
    document.getElementById('modalTitle').textContent = context === 'comparison' ? 'Add Product Code for Comparison' : 'Add New Product Code';
    document.getElementById('newCodeInput').value = '';
    document.getElementById('addCodeModal').classList.remove('hidden');
    document.getElementById('newCodeInput').focus();
}

function closeAddCodeModal() {
    document.getElementById('addCodeModal').classList.add('hidden');
}

function confirmAddCode() {
    const code = document.getElementById('newCodeInput').value.trim().toUpperCase();
    const context = document.getElementById('modalContext').value;
    
    if (code && code.length >= 2 && code.length <= 10) {
        if (!availableCodes.includes(code)) {
            availableCodes.push(code);
            if (context === 'comparison') {
                if (!comparisonCodes.A) {
                    comparisonCodes.A = code;
                } else if (!comparisonCodes.B) {
                    comparisonCodes.B = code;
                }
            } else {
                selectedCode = code;
            }
            renderProductSelectors();
            renderProductChips();
            closeAddCodeModal();
            
            if (context === 'comparison') {
                loadComparisonData();
            } else {
                loadAllData();
            }
        } else {
            alert('Product code already exists');
        }
    } else {
        alert('Please enter a valid product code (2-10 characters)');
    }
}

function updateComparisonDisplay() {
    document.getElementById('comparison-codes').textContent = `Comparing: ${comparisonCodes.A} vs ${comparisonCodes.B}`;
}

function loadAllData() {
    load510kData();
    loadAdverseEventData();
    loadRecallData();
}

// 在 loadAllData 函数中添加错误处理
async function load510kData() {
    if (!selectedCode) {
        showMessage('Please select a product code', 'warning');
        return;
    }
    
    const loading = document.getElementById('510k-loading');
    const table = document.getElementById('510k-table');
    
    loading.classList.remove('hidden');
    table.innerHTML = '';
    
    try {
        const response = await fetch('/api/fda/510k', {
            method: 'POST',
            headers: {'Content-Type': 'application/json'},
            body: JSON.stringify({
                product_code: selectedCode, 
                limit: 10
            })
        });
        
        const data = await response.json();
        
        if (data.status === 'success') {
            document.getElementById('510k-product-code').textContent = data.product_code;
            document.getElementById('510k-total').textContent = data.total;
            document.getElementById('510k-last-updated').textContent = data.last_updated || 'N/A';
            
            if (data.records && data.records.length > 0) {
                render510kTable(data.records);
            } else {
                table.innerHTML = `
                    <div class="text-center py-8">
                        <div class="text-gray-400 mb-2">
                            <i class="fas fa-database text-3xl"></i>
                        </div>
                        <p class="text-gray-500">No 510(k) records found for product code <strong>${selectedCode}</strong></p>
                        <p class="text-sm text-gray-400 mt-2">Try a different product code like GEI, GEX, or PBX</p>
                    </div>
                `;
            }
        } else {
            showMessage(data.message || 'Error loading 510(k) data', 'error');
            table.innerHTML = `<p class="text-gray-500">${data.message || 'No data available'}</p>`;
        }
    } catch (error) {
        console.error('Error loading 510(k) data:', error);
        showMessage('Network error loading data', 'error');
        table.innerHTML = `
            <div class="text-center py-8">
                <div class="text-red-400 mb-2">
                    <i class="fas fa-exclamation-triangle text-3xl"></i>
                </div>
                <p class="text-red-500">Error loading data</p>
                <button onclick="load510kData()" class="mt-2 px-3 py-1 bg-gray-100 text-gray-700 rounded text-sm hover:bg-gray-200">
                    Retry
                </button>
            </div>
        `;
    } finally {
        loading.classList.add('hidden');
    }
}

function render510kTable(records) {
    const table = document.getElementById('510k-table');
    
    if (!records || records.length === 0) {
        table.innerHTML = '<p class="text-gray-500">No records found</p>';
        return;
    }
    
    let html = `
        <table class="min-w-full divide-y divide-gray-200">
            <thead class="bg-gray-50">
                <tr>
                    <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">K Number</th>
                    <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Device Name</th>
                    <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Product Code</th>
                    <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Decision Date</th>
                    <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Applicant</th>
                </tr>
            </thead>
            <tbody class="bg-white divide-y divide-gray-200">
    `;
    
    records.forEach(record => {
        html += `
            <tr class="hover:bg-gray-50">
                <td class="px-4 py-3 text-sm text-gray-900 font-medium">${record.k_number}</td>
                <td class="px-4 py-3 text-sm text-gray-900">${record.device_name}</td>
                <td class="px-4 py-3 text-sm"><span class="px-2 py-1 bg-indigo-100 text-indigo-800 rounded text-xs">${record.product_code}</span></td>
                <td class="px-4 py-3 text-sm text-gray-900">${record.decision_date}</td>
                <td class="px-4 py-3 text-sm text-gray-900">${record.applicant}</td>
            </tr>
        `;
    });
    
    html += '</tbody></table>';
    table.innerHTML = html;
}

async function loadAdverseEventData() {
    if (!selectedCode) return;
    
    const loading = document.getElementById('adverse-loading');
    loading.classList.remove('hidden');
    
    try {
        const response = await fetch('/api/fda/adverse-events', {
            method: 'POST',
            headers: {'Content-Type': 'application/json'},
            body: JSON.stringify({product_code: selectedCode})
        });
        
        const data = await response.json();
        
        if (data.status === 'success') {
            document.getElementById('adverse-product-code').textContent = `Product Code: ${data.product_code}`;
            document.getElementById('adverse-total').textContent = data.total;
            renderAdverseEventCharts(data);
        }
    } catch (error) {
        console.error('Error loading adverse event data:', error);
    } finally {
        loading.classList.add('hidden');
    }
}

function renderAdverseEventCharts(data) {
    // Event Type Chart
    if (charts.eventType) charts.eventType.destroy();
    charts.eventType = new Chart(document.getElementById('eventTypeChart'), {
        type: 'bar',
        data: {
            labels: data.by_event_type.map(item => item.term),
            datasets: [{
                label: 'Count',
                data: data.by_event_type.map(item => item.count),
                backgroundColor: 'rgba(99, 102, 241, 0.8)'
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: true,
            plugins: {
                legend: { display: false }
            }
        }
    });
    
    // Report Source Chart
    if (charts.reportSource) charts.reportSource.destroy();
    charts.reportSource = new Chart(document.getElementById('reportSourceChart'), {
        type: 'pie',
        data: {
            labels: data.by_report_source.map(item => item.term),
            datasets: [{
                data: data.by_report_source.map(item => item.count),
                backgroundColor: ['#6366f1', '#8b5cf6', '#ec4899', '#f59e0b', '#10b981']
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: true,
            plugins: {
                legend: { position: 'right' }
            }
        }
    });
    
    // Annual Trends Chart
    if (charts.adverseTrend) charts.adverseTrend.destroy();
    charts.adverseTrend = new Chart(document.getElementById('adverseTrendChart'), {
        type: 'line',
        data: {
            labels: data.by_year.map(item => item.year),
            datasets: [{
                label: 'Adverse Events',
                data: data.by_year.map(item => item.count),
                borderColor: 'rgb(99, 102, 241)',
                backgroundColor: 'rgba(99, 102, 241, 0.1)',
                tension: 0.4,
                fill: true
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: true,
            scales: {
                y: { beginAtZero: true }
            }
        }
    });
}

async function loadRecallData() {
    if (!selectedCode) return;
    
    const loading = document.getElementById('recall-loading');
    loading.classList.remove('hidden');
    
    try {
        const response = await fetch('/api/fda/recalls', {
            method: 'POST',
            headers: {'Content-Type': 'application/json'},
            body: JSON.stringify({product_code: selectedCode})
        });
        
        const data = await response.json();
        
        if (data.status === 'success') {
            document.getElementById('recall-product-code').textContent = `Product Code: ${data.product_code}`;
            document.getElementById('recall-total').textContent = data.total;
            renderRecallCharts(data);
        }
    } catch (error) {
        console.error('Error loading recall data:', error);
    } finally {
        loading.classList.add('hidden');
    }
}

function renderRecallCharts(data) {
    // Classification Chart
    if (charts.classification) charts.classification.destroy();
    charts.classification = new Chart(document.getElementById('classificationChart'), {
        type: 'doughnut',
        data: {
            labels: data.by_classification.map(item => item.term),
            datasets: [{
                data: data.by_classification.map(item => item.count),
                backgroundColor: ['#ef4444', '#f59e0b', '#10b981']
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: true,
            plugins: {
                legend: { position: 'right' }
            }
        }
    });
    
    // Status Chart
    if (charts.status) charts.status.destroy();
    charts.status = new Chart(document.getElementById('statusChart'), {
        type: 'bar',
        data: {
            labels: data.by_status.map(item => item.term),
            datasets: [{
                label: 'Count',
                data: data.by_status.map(item => item.count),
                backgroundColor: 'rgba(139, 92, 246, 0.8)'
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: true,
            plugins: {
                legend: { display: false }
            }
        }
    });
    
    // Root Cause Chart
    if (charts.rootCause) charts.rootCause.destroy();
    charts.rootCause = new Chart(document.getElementById('rootCauseChart'), {
        type: 'bar',
        data: {
            labels: data.by_root_cause.slice(0, 10).map(item => item.term),
            datasets: [{
                label: 'Count',
                data: data.by_root_cause.slice(0, 10).map(item => item.count),
                backgroundColor: 'rgba(236, 72, 153, 0.8)'
            }]
        },
        options: {
            indexAxis: 'y',
            responsive: true,
            maintainAspectRatio: true,
            plugins: {
                legend: { display: false }
            }
        }
    });
}

async function loadComparisonData() {
    if (!comparisonCodes.A || !comparisonCodes.B) {
        alert('Please select two product codes to compare');
        return;
    }
    
    if (comparisonCodes.A === comparisonCodes.B) {
        alert('Please select two different product codes to compare');
        return;
    }
    
    const loading = document.getElementById('comparison-loading');
    const metricsContainer = document.getElementById('comparison-metrics');
    
    loading.classList.remove('hidden');
    metricsContainer.innerHTML = '';
    
    try {
        const response = await fetch('/api/fda/compare', {
            method: 'POST',
            headers: {'Content-Type': 'application/json'},
            body: JSON.stringify({product_codes: [comparisonCodes.A, comparisonCodes.B]})
        });
        
        const data = await response.json();
        
        if (data.status === 'success') {
            document.getElementById('comparison-codes').textContent = `Comparing: ${comparisonCodes.A} vs ${comparisonCodes.B}`;
            renderComparison(data.products);
        }
    } catch (error) {
        console.error('Error loading comparison data:', error);
        metricsContainer.innerHTML = '<p class="text-red-500">Error loading comparison data</p>';
    } finally {
        loading.classList.add('hidden');
    }
}

function renderComparison(products) {
    // Update metrics display
    const metricsContainer = document.getElementById('comparison-metrics');
    metricsContainer.innerHTML = '';
    
    products.forEach((product, index) => {
        const metricDiv = document.createElement('div');
        metricDiv.className = 'bg-white rounded-lg border border-gray-200 p-4';
        metricDiv.innerHTML = `
            <div class="text-center mb-3">
                <span class="inline-block px-3 py-1 rounded-full ${index === 0 ? 'bg-blue-100 text-blue-800' : 'bg-purple-100 text-purple-800'} text-sm font-medium">
                    ${product.product_code}
                </span>
            </div>
            <div class="space-y-3">
                <div>
                    <div class="text-xs text-gray-500">Adverse Events</div>
                    <div class="text-xl font-bold">${product.adverse_events.toLocaleString()}</div>
                </div>
                <div>
                    <div class="text-xs text-gray-500">Recalls</div>
                    <div class="text-xl font-bold">${product.recalls.toLocaleString()}</div>
                </div>
                <div>
                    <div class="text-xs text-gray-500">Latest 510(k)</div>
                    <div class="text-sm font-medium">${product.latest_510k || 'N/A'}</div>
                </div>
            </div>
        `;
        metricsContainer.appendChild(metricDiv);
    });
    
    // Add comparison summary
    const summaryDiv = document.createElement('div');
    summaryDiv.className = 'bg-gray-50 rounded-lg border border-gray-200 p-4';
    summaryDiv.innerHTML = `
        <div class="text-center mb-3">
            <span class="text-sm font-medium text-gray-700">Comparison Ratio</span>
        </div>
        <div class="space-y-3">
            <div>
                <div class="text-xs text-gray-500">Adverse Events Ratio</div>
                <div class="text-lg font-bold">${(products[0].adverse_events / Math.max(products[1].adverse_events, 1)).toFixed(2)}:1</div>
            </div>
            <div>
                <div class="text-xs text-gray-500">Recall Ratio</div>
                <div class="text-lg font-bold">${(products[0].recalls / Math.max(products[1].recalls, 1)).toFixed(2)}:1</div>
            </div>
        </div>
    `;
    metricsContainer.appendChild(summaryDiv);
    
    // Render comparison charts
    renderComparisonCharts(products);
}

function renderComparisonCharts(products) {
    // Chart 1: Adverse Events vs Recalls
    if (charts.comparison1) charts.comparison1.destroy();
    charts.comparison1 = new Chart(document.getElementById('comparisonChart1'), {
        type: 'bar',
        data: {
            labels: [products[0].product_code, products[1].product_code],
            datasets: [
                {
                    label: 'Adverse Events',
                    data: [products[0].adverse_events, products[1].adverse_events],
                    backgroundColor: 'rgba(99, 102, 241, 0.8)'
                },
                {
                    label: 'Recalls',
                    data: [products[0].recalls, products[1].recalls],
                    backgroundColor: 'rgba(239, 68, 68, 0.8)'
                }
            ]
        },
        options: {
            responsive: true,
            maintainAspectRatio: true,
            scales: {
                y: { beginAtZero: true }
            }
        }
    });
    
    // Chart 2: Latest 510(k) dates (if available)
    if (charts.comparison2) charts.comparison2.destroy();
    
    const dates = products.map(p => {
        if (p.latest_510k && p.latest_510k !== 'N/A') {
            return new Date(p.latest_510k).getTime();
        }
        return null;
    });
    
    if (dates[0] && dates[1]) {
        charts.comparison2 = new Chart(document.getElementById('comparisonChart2'), {
            type: 'bar',
            data: {
                labels: [products[0].product_code, products[1].product_code],
                datasets: [{
                    label: 'Latest 510(k) Date (timestamp)',
                    data: dates,
                    backgroundColor: ['rgba(16, 185, 129, 0.8)', 'rgba(245, 158, 11, 0.8)']
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: true,
                scales: {
                    y: {
                        ticks: {
                            callback: function(value) {
                                return new Date(value).toLocaleDateString();
                            }
                        }
                    }
                }
            }
        });
    }
    
    // Chart 3: Safety Metrics Summary
    if (charts.comparison3) charts.comparison3.destroy();
    charts.comparison3 = new Chart(document.getElementById('comparisonChart3'), {
        type: 'radar',
        data: {
            labels: ['Adverse Events', 'Recalls', 'Safety Score'],
            datasets: [
                {
                    label: products[0].product_code,
                    data: [
                        Math.min(products[0].adverse_events, 100),
                        Math.min(products[0].recalls * 10, 100),
                        Math.max(100 - (products[0].adverse_events + products[0].recalls * 10), 0)
                    ],
                    borderColor: 'rgb(59, 130, 246)',
                    backgroundColor: 'rgba(59, 130, 246, 0.2)'
                },
                {
                    label: products[1].product_code,
                    data: [
                        Math.min(products[1].adverse_events, 100),
                        Math.min(products[1].recalls * 10, 100),
                        Math.max(100 - (products[1].adverse_events + products[1].recalls * 10), 0)
                    ],
                    borderColor: 'rgb(168, 85, 247)',
                    backgroundColor: 'rgba(168, 85, 247, 0.2)'
                }
            ]
        },
        options: {
            responsive: true,
            maintainAspectRatio: true,
            scales: {
                r: { beginAtZero: true, max: 100 }
            }
        }
    });
}

function switchTab(tabName) {
    document.querySelectorAll('.tab-content').forEach(tab => tab.classList.add('hidden'));
    document.querySelectorAll('.tab-button').forEach(btn => {
        btn.classList.remove('border-indigo-600', 'text-indigo-600');
        btn.classList.add('border-transparent', 'text-gray-500');
    });
    
    document.getElementById(`tab-${tabName}`).classList.remove('hidden');
    event.target.classList.add('border-indigo-600', 'text-indigo-600');
    event.target.classList.remove('border-transparent', 'text-gray-500');
}

function exportToCSV() {
    alert('CSV export functionality will be implemented');
}

function exportToExcel() {
    alert('Excel export functionality will be implemented');
}
</script>
{% endblock %}